const { DataTypes } = require("sequelize");
const sequelize = require("../db/connect");

const Good = sequelize.define("good", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  avatar: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  introduction: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  price: {
    type: DataTypes.DECIMAL,
    allowNull: false,
  },
  stock_quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  tagId: {
    type: DataTypes.INTEGER,
    allowNull: true,
  },
  imageList: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  // 作者
  author: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  isRecommend: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

const Sku = sequelize.define("sku", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  goodId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  amount: {
    type: DataTypes.DECIMAL,
    allowNull: false,
  },
  stock_quantity: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

const Tag = sequelize.define("tag", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

// 建立联系
Good.belongsTo(Tag, {
  foreignKey: "tagId",
  targetKey: "id",
});
Tag.hasMany(Good, {
  foreignKey: "tagId",
  targetKey: "id",
});

Good.hasMany(Sku, {
  foreignKey: "goodId",
  targetKey: "id",
});
Sku.belongsTo(Good, {
  foreignKey: "goodId",
  targetKey: "id",
});

module.exports = {
  Good,
  Sku,
  Tag,
};
